<template>
  <el-dialog
    title="出库分配"
    :visible.sync="dialogTablesVisible"
    :modal-append-to-body="false"
    id="equipments"
  >
    <template>
      <el-tabs v-model="activeName" type="card" id="tabCard" @tab-click="handleClick">
        <el-tab-pane label="扫码分配" name="first">
          <div v-if="activeName === 'first'">
            <el-steps :active="disc_current" simple finish-status="success">
              <el-step title="选择移库设备"></el-step>
              <el-step title="选择下级库位"></el-step>
              <el-step title="移库完成"></el-step>
            </el-steps>
            <!-- 第一步分开分配 -->
            <el-row :gutter="20" id="firstCard" v-if="disc_current === 1 && activeName === 'first'">
              <div class="firststorage">
                <el-form :model="forms" @submit.native.prevent>
                  <el-input
                    v-model="forms.imei"
                    @keyup.13.native="enterImei(forms.imei)"
                    placeholder="请通过扫码枪或手动添加获取IMEI号"
                    ref="inputs"
                  ></el-input>
                </el-form>
                <el-button type="primary" slot="append" @click="enterImei(forms.imei)">添加</el-button>
              </div>
              <div v-if="show_one" style="margin: 97px auto 0px;text-align: center;">
                <img src="../../../../../static/image/device/b-yellow.png">
                <div
                  style="font-size:12px;font-weight:400;color:rgba(153,153,153,1);padding-bottom: 30px;"
                >暂无设备</div>
              </div>
              <vue-scroll :ops="ops" v-show="!show_one">
                <div style="padding:0px;margin-top: 30px;width: 100%;">
                  <div
                    v-for="(item,index) in searchImei"
                    :key="index"
                    style="float: left;width: 280px;height: 50px;margin: 0 7px 15px 7px;box-shadow: 0px 4px 18px rgba(69, 71, 74, 0.1);background: #fff;line-height: 50px;font-size:18px; font-weight:bold;"
                  >
                    <img
                      src="../../../../../static/image/device/shebei-1.png"
                      style="float:left;margin:8px 5px 0px 12px;"
                    >
                    {{item.imei}}
                    <img
                      src="../../../../../static/image/device/delect_equment.png"
                      style="float:right;margin:16px;"
                      @click="delectImei(item.imei)"
                    >
                  </div>
                </div>
              </vue-scroll>
            </el-row>
            <!-- 第二步 -->
            <el-row
              :gutter="20"
              style="margin-top:30px !important;background:#F8F8F8;"
              v-if="disc_current === 2 &&activeName === 'first'"
            >
              <vue-scroll :ops="ops">
                <div
                  style="width: 100%;display: inline-block;box-sizing: border-box;height:450px;padding:0 27px 30px"
                >
                  <el-col
                    :site="tableSite"
                    :span="4"
                    v-for="(item,index) in tableSite"
                    :key="index"
                    style="width:20%;padding:0"
                  >
                    <div class="grid-content" style="margin: 30px 13px 0px;">
                      <el-button
                        type="info"
                        size="medium"
                        round
                        @click="click_disc_current(index)"
                        :class="disc_active === index ? 'btn-current':''"
                        style="width:156px;border: 1px solid rgba(217,217,217,1);background:#fff;border-color:#fff;color:#8891A2;white-space: nowrap;text-overflow: ellipsis;overflow:hidden;height: 36px;font-size: 14px;"
                      >{{item.name}}</el-button>
                    </div>
                  </el-col>
                </div>
              </vue-scroll>
            </el-row>
            <div class="dialog-footer footer" v-if="disc_current !== 3 &&activeName === 'first'">
              <el-button
                type="primary"
                class="btnClosed"
                @click="closeDisc"
              >{{disc_current === 2 ? "上一步" : '取消'}}</el-button>
              <el-button
                type="primary"
                @click="next"
                :disabled="can_next"
                class="btnSaved"
                :class="{btnAdd:!can_next,add:can_next}"
              >下一步</el-button>
            </div>
            <!-- 第三步 -->
            <el-row
              :gutter="20"
              style="margin:30px 0 0px 0; "
              v-if="disc_current === 3 &&activeName === 'first'"
            >
              <img
                src="../../../../../static/image/device/b-red.png"
                alt
                style="margin: 20px auto;display: block;"
              >
              <p style="text-align: center;">已移库完成，3s后将自动关闭弹窗</p>
            </el-row>
          </div>
        </el-tab-pane>
        <el-tab-pane label="整箱分配" name="second">
          <div v-if="activeName === 'second'">
            <el-steps :active="disc_current" simple finish-status="success">
              <el-step title="选择移库设备"></el-step>
              <el-step title="选择下级库位"></el-step>
              <el-step title="移库完成"></el-step>
            </el-steps>
            <!-- 第一步分开分配 -->
            <el-row id="firstCard" v-if="disc_current === 1&&activeName === 'second'">
              <div class="firststorage">
                <el-form :model="set" @submit.native.prevent>
                  <el-input
                    v-model="set.box_number"
                    @keyup.13.native="enterBox(set.box_number)"
                    placeholder="请通过扫码枪或手动添加获取箱号"
                    ref="inputsbox"
                  ></el-input>
                </el-form>
                <el-button type="primary" slot="append" @click="enterBox(set.box_number)">添加</el-button>
              </div>
              <div v-if="show_one" style="margin: 97px auto 0px;text-align: center;">
                <img src="../../../../../static/image/device/b-yellow.png">
                <div
                  style="font-size:12px;font-weight:400;color:rgba(153,153,153,1);padding-bottom: 30px;"
                >暂无设备</div>
              </div>
              <vue-scroll :ops="ops" v-show="!show_one">
                <div style="padding:0px;margin-top: 30px;width: 100%;">
                  <div
                    v-for="item in arrbox"
                    :key="item.key"
                    style="float: left;width: 280px;height: 50px;margin: 0 7px 15px 7px;box-shadow: 0px 4px 18px rgba(69, 71, 74, 0.1);background: #fff;line-height: 50px;font-size:18px; font-weight:bold;"
                  >
                    <img
                      src="../../../../../static/image/device/shebei-1.png"
                      style="float:left;margin:8px 5px 0px 12px;"
                    >
                    {{item}}
                    <img
                      src="../../../../../static/image/device/delect_equment.png"
                      style="float:right;margin:16px;"
                      @click="delectBox(item)"
                    >
                  </div>
                </div>
              </vue-scroll>
            </el-row>
            <!-- 第二步 -->
            <el-row
              :gutter="20"
              style="margin-top:30px!important;background:F8F8F8;"
              v-if="disc_current === 2&&activeName === 'second'"
            >
              <vue-scroll :ops="ops">
                <div
                  style="width: 100%;display: inline-block;box-sizing: border-box;height:450px;padding:0 27px 30px"
                >
                  <el-col
                    :site="tableSite"
                    :span="4"
                    v-for="(item,index) in tableSite"
                    :key="index"
                    style="width:20%;padding:0"
                  >
                    <div class="grid-content" style="margin: 30px 13px 0px; ">
                      <el-button
                        type="info"
                        size="medium"
                        round
                        @click="click_disc_current(index)"
                        :class="disc_active === index ? 'btn-current':''"
                        style="width:156px;border: 1px solid rgba(217,217,217,1);background:#fff;border-color:#fff;color:#8891A2;white-space: nowrap;text-overflow: ellipsis;overflow:hidden;height: 36px;font-size: 14px;"
                      >{{item.name}}</el-button>
                    </div>
                  </el-col>
                </div>
              </vue-scroll>
            </el-row>
            <div class="dialog-footer footer" v-if="disc_current !== 3&&activeName === 'second'">
              <el-button
                type="primary"
                class="btnClosed"
                @click="closeDisc"
              >{{disc_current === 2 ? "上一步" : '取消'}}</el-button>
              <el-button
                type="primary"
                @click="next"
                :disabled="can_next"
                class="btnSaved"
                :class="{btnAdd:!can_next,add:can_next}"
              >下一步</el-button>
            </div>
            <!-- 第三步 -->
            <el-row
              :gutter="20"
              style="margin:30px 0 0px 0;"
              v-if="disc_current === 3&&activeName === 'second'"
            >
              <img
                src="../../../../../static/image/device/b-red.png"
                alt
                style="margin: 20px auto;display: block;"
              >
              <p style="text-align: center;">已移库完成，3s后将自动关闭弹窗</p>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
    </template>
  </el-dialog>
</template>
<script>
import Config from "../../../../config";
import { resolve } from "url";
import { rejects } from "assert";
import qs from "qs";
import { mapGetters } from "vuex";
export default {
  name: "Dispathequment",
  props: ["messagedispath"],
  data() {
    return {
      ops: {
        bar: {
          background: "#DDDEE0"
        }
      },
      //弹框数据
      form: {},
      // 出库分配弹框
      dialogTablesVisible: false,
      // 选择第二步点击添加颜色
      disc_active: null,
      disc_current: 1,
      //出库分配tab切换
      activeName: "first",
      forms: {
        imei: ""
      },
      set: {
        box_number: ""
      },
      show_one: true,
      searchImei: [], //扫码数据
      arrbox: [], //分配盒子
      saveArr: [],
      // 获取库房站点
      tableSite: [],
      imeiDatas: [],
      boxDatas: [],
      id: "",
      centerDialogVisible: false,
      arr_flag: [],
      checked: false,
      save_flag: "",
      imei_flag: "",
      // 数组去重盒子
      boxArr: []
    };
  },
  methods: {
    // imei搜索
    imei_asd() {
      return new Promise((resolve, reject) => {
        // 搜索imei admin
        let url = `${Config.DEVICE_MANAGE_URL}/device_house_user/query`;
        let paramimei = {
          devtype: Config.objType.devtype,
          devname: Config.objType.devname
        };
        // 西安test
        let paramimeitest = {
          devtype: Config.objType.devtype,
          devname: Config.objType.devname,
          country: 86,
          housetype: "test"
        };
        //其余的
        let paramimeiother = {
          devtype: Config.objType.devtype,
          devname: Config.objType.devname,
          country: 86,
          housetype: "official"
        };
        // 省库管
        let paramimeiprovin = {
          devtype: Config.objType.devtype,
          devname: Config.objType.devname,
          province: this.district.districtId,
          country: 86,
          housetype: "official"
        };
        // 市库管
        let paramimeicity = {
          devtype: Config.objType.devtype,
          devname: Config.objType.devname,
          city: this.district.districtId,
          country: 86,
          housetype: "official"
        };
        //扫码
        if (this.forms) {
          for (var item in this.forms) {
            if (this.forms[item]) {
              paramimei[item] = this.forms[item];
            }
          }
        }
        if (this.set) {
          for (var item in this.set) {
            if (this.set[item]) {
              paramimei[item] = this.set[item];
            }
          }
        }
        //省
        if (this.forms) {
          for (var item in this.forms) {
            if (this.forms[item]) {
              paramimeiprovin[item] = this.forms[item];
            }
          }
        }
        if (this.set) {
          for (var item in this.set) {
            if (this.set[item]) {
              paramimeiprovin[item] = this.set[item];
            }
          }
        }
        //市
        if (this.forms) {
          for (var item in this.forms) {
            if (this.forms[item]) {
              paramimeicity[item] = this.forms[item];
            }
          }
        }
        if (this.set) {
          for (var item in this.set) {
            if (this.set[item]) {
              paramimeicity[item] = this.set[item];
            }
          }
        }
        // test
        if (this.forms) {
          for (var item in this.forms) {
            if (this.forms[item]) {
              paramimeitest[item] = this.forms[item];
            }
          }
        }
        if (this.set) {
          for (var item in this.set) {
            if (this.set[item]) {
              paramimeitest[item] = this.set[item];
            }
          }
        }
        // 其余
        if (this.forms) {
          for (var item in this.forms) {
            if (this.forms[item]) {
              paramimeiother[item] = this.forms[item];
            }
          }
        }
        if (this.set) {
          for (var item in this.set) {
            if (this.set[item]) {
              paramimeiother[item] = this.set[item];
            }
          }
        }
        if (this.role[0].sort === 2) {
          if (this.district.districtType === 2) {
            this.$http.get(url, paramimeiprovin).then(res => {
              resolve(res);
            });
          } else {
            this.$http.get(url, paramimeicity).then(res => {
              resolve(res);
            });
          }
        } else if (this.role[0].sort === 5) {
          this.$http.get(url, paramimeitest).then(res => {
            resolve(res);
          });
        } else if (this.role[0].sort === 4) {
          this.$http.get(url, paramimei).then(res => {
            resolve(res);
          });
        } else {
          this.$http.get(url, paramimeiother).then(res => {
            resolve(res);
          });
        }
      });
    },
    // 扫码搜索imei
    asd() {
      return new Promise((resolve, reject) => {
        this.imei_asd().then(res => {
          if (res.array.length) {
            if (
              res.array[0].dev_equip_id === null ||
              res.array[0].dev_equip_id === ""
            ) {
              // 设置flag 判断库位一致
              if (!this.imei_flag) {
                this.imei_flag = res.array[0].storehouses_name;
              }
              if (this.imei_flag !== res.array[0].storehouses_name) {
                this.$message.error("库位不一致");
                return;
              } else {
                this.searchImei.push(res.array[0]);
                this.show_one = false;
                this.forms.imei = "";
              }
            } else {
              this.$message.error("该设备已被分配");
              this.forms.imei = "";
            }
          } else {
            this.$message("暂无");
            this.forms.imei = "";
          }
          resolve();
        });
      });
    },
    search_imei(value) {
      return new Promise((resolve, reject) => {
        if (value) {
          var a = 0;
          if (!this.searchImei.length) {
            this.asd().then(() => {
              resolve();
            });
          } else {
            this.searchImei.map((item, i) => {
              if (item.imei === value) {
                a++;
                this.forms.imei = "";
                this.$message({
                  message: "IMEI重复",
                  type: "warning"
                });
              }
            });
            if (!a) {
              this.asd().then(() => {
                resolve();
              });
            }
          }
        }
      });
    },
    // 分配扫码监听input框
    enterImei(value) {
      this.search_imei(value).then(() => {
        this.getImei();
      });
    },
    getImei() {
      // 获取imei库房站点
      let url = `${Config.DEVICE_MANAGE_URL}/storehouses/query_sub_by_name`;
      let param_by_imei = {
        page: 0,
        size: 100,
        devtype: Config.objType.devtype,
        devname: Config.objType.devname,
        name: this.searchImei[0].storehouses_name
      };
      this.$http.get(url, param_by_imei).then(res => {
        this.tableSite = res.array;
      });
    },
    // 扫码删除
    delectImei(value) {
      this.searchImei.map((item, i) => {
        if (item.imei === value) {
          this.searchImei.splice(i, 1);
        }
      });
      this.$message({ type: "success", message: "删除成功!" });
      if (this.searchImei.length == 0) {
        this.imei_flag = "";
      }
    },
    // 扫码搜索box
    boxs() {
      return new Promise((resolve, reject) => {
        this.imei_asd().then(res => {
          this.saveArr = res.array;
          if (res.array.length) {
            if (
              res.array[0].dev_equip_id === null ||
              res.array[0].dev_equip_id === ""
            ) {
              // 数组去重
              this.boxArr = this.saveArr.map(item => {
                return item.storehouses_name;
              });
              if (Array.from(new Set(this.boxArr)).length === 1) {
                console.log(this.boxArr);
                if (!this.save_flag) {
                  this.save_flag = this.boxArr[0];
                }
                if (this.boxArr[0] !== this.save_flag) {
                  this.$message.error("库位不一致");
                  return;
                } else {
                  this.arrbox.push(this.set.box_number);
                  this.show_one = false;
                  this.set.box_number = "";
                }
              } else {
                console.log(this.boxArr);
                this.$message.error("库位不一致");
                return;
              }
            } else {
              this.$message.error("该设备已被分配");
              this.set.box_number = "";
            }
          } else {
            this.$message("暂无");
            this.set.box_number = "";
          }
          resolve();
        });
      });
    },
    search_box(value) {
      return new Promise((resolve, reject) => {
        if (value) {
          var a = 0;
          if (!this.arrbox.length) {
            this.boxs().then(() => {
              resolve();
            });
          } else {
            this.arrbox.map((item, i) => {
              if (item === value) {
                a++;
                this.set.box_number = "";
                this.$message({
                  message: "箱号重复",
                  type: "warning"
                });
              }
            });
            if (!a) {
              this.boxs().then(() => {
                resolve();
              });
            }
          }
        }
      });
    },
    // 分配扫码监听input框
    enterBox(value) {
      this.search_box(value).then(() => {
        this.getBox();
      });
    },
    getBox() {
      let url = `${Config.DEVICE_MANAGE_URL}/storehouses/query_sub_by_name`;
      let param_by_box = {
        page: 0,
        size: 100,
        devtype: Config.objType.devtype,
        devname: Config.objType.devname,
        name: Array.from(new Set(this.boxArr)).toString()
      };
      this.$http.get(url, param_by_box).then(res => {
        this.tableSite = res.array;
      });
    },
    // 扫码删除
    delectBox(value) {
      this.arrbox.map((item, i) => {
        if (item === value) {
          this.arrbox.splice(i, 1);
        }
      });
      this.$message({ type: "success", message: "删除成功!" });
      if (this.arrbox.length == 0) {
        this.save_flag = "";
      }
    },
    // 出库分配点击切换
    handleClick() {
      this.disc_current = 1;
      this.show_one = true;
      if (this.activeName === "first") {
        this.$nextTick(() => {
          this.$refs.inputs.focus();
        });
        this.show_one = false;
        this.imei_flag = "";
      } else {
        this.$nextTick(() => {
          this.$refs.inputsbox.focus();
        });
        this.save_flag = "";
        this.show_one = false;
      }
    },
    // 颜色切换
    click_disc_current(index) {
      // console.log(index);
      this.disc_active = index;
      // console.log(this.tableSite[this.disc_active]);
    },
    //imei分配装箱
    next() {
      // 点击下一步
      if (this.disc_current === 1) {
        this.disc_current = 2;
        this.show_one = false;
        // this.getSiteData();
      } else {
        this.$confirm("确定下一步吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(value => {
            if (value) {
              // 扫码分配
              if (this.activeName === "first") {
                this.postimei();
              } else {
                // 整箱分配
                this.postbox();
              }
              setTimeout(() => {
                this.dialogTablesVisible = false;
              }, 3000);
            }
            this.$message({
              type: "success",
              message: "分配成功!"
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消分配"
            });
          });
      }
    },
    postimei() {
      // 扫码获取imei
      this.searchImei.map(item => {
        this.imeiDatas.push(item.imei);
      });
      let url = `${
        Config.DEVICE_MANAGE_URL
      }/inventory/store_house_dispath_by_imei`;
      this.$http
        .post(
          url,
          qs.stringify({
            devtype: Config.objType.devtype,
            devname: Config.objType.devname,
            imeis: this.imeiDatas.toString(),
            current_owner: this.tableSite[this.disc_active].name,
            current_owner_id: this.tableSite[this.disc_active].id
          }),
          { "Content-Type": "application/x-www-form-urlencoded" }
        )
        .then(res => {
          // console.log(res);
          this.disc_current = 3;
          this.imeiDatas = [];
          this.getListData();
        });
    },
    // 整箱分配提交
    postbox() {
      this.arrbox.map(item => {
        this.boxDatas.push(item);
      });
      let url = `${
        Config.DEVICE_MANAGE_URL
      }/inventory/store_house_dispath_by_box`;
      this.$http
        .post(
          url,
          qs.stringify({
            devtype: Config.objType.devtype,
            devname: Config.objType.devname,
            boxs: this.boxDatas.toString(),
            current_owner: this.tableSite[this.disc_active].name,
            current_owner_id: this.tableSite[this.disc_active].id
          }),
          { "Content-Type": "application/x-www-form-urlencoded" }
        )
        .then(res => {
          this.disc_current = 3;
          this.boxDatas = [];
          this.getListData();
        });
    },
    closeDisc() {
      if (this.disc_current === 1) {
        this.dialogTablesVisible = false;
      } else if (this.disc_current === 2) {
        this.disc_current = 1;
      } else {
        this.dialogTablesVisible = false;
      }
    }
  },
  computed: {
    can_next() {
      if (this.disc_current === 1) {
        if (
          this.arrbox.filter(res => res).length ||
          this.searchImei.filter(res => res.imei).length
        ) {
          if (this.a) {
            return true;
          }
          return false;
        } else {
          return true;
        }
      }
      if (this.disc_current === 2) {
        if (this.disc_active === -1) {
          return true;
        } else {
          return false;
        }
      }
    },
    ...mapGetters("user", {
      district: "getDistrict",
      role: "getRole"
    })
  },
  watch: {
    messagedispath(data) {
      if (data) {
        this.dialogTablesVisible = data;
        this.a = 0;
        // 扫码imei
        this.searchImei = [];
        this.forms.imei = "";
        this.set.box_number = "";
        this.arrbox = [];
        this.disc_active = -1;
        this.show_one = true;
        this.activeName = "first";
        this.dialogTablesVisible = true;
        this.disc_current = 1;
        this.save_flag = "";
        this.imei_flag = "";
        // 自动获取焦点
        this.$nextTick(() => {
          this.$refs.inputs.focus();
        });
        this.boxDatas = [];
        this.imeiDatas = [];
      }
    },

    // 弹框关闭
    dialogTablesVisible(data) {
      if (!data) {
        // 子向父
        this.$emit("listendispath", false);
      }
    }
  }
};
</script>